from PySide6.QtCore import QThread, Signal
import telnetlib3
from .base_thread import BaseThread

class TelnetThread(BaseThread):
    def __init__(self, host, port):
        super().__init__()
        self.host = host
        self.port = int(port)
        self.client = None
    
    def _connect(self):
        try:
            import asyncio
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            reader, writer = loop.run_until_complete(
                telnetlib3.open_connection(self.host, self.port)
            )
            self.client = (reader, writer)
            self._is_running = True
            self.connected.emit(True)
            return True
        except Exception as e:
            self.error.emit(str(e))
            self.connected.emit(False)
            return False
    
    def _disconnect(self):
        self._is_running = False
        if self.client:
            try:
                self.client.close()
            except:
                pass
            self.client = None
        self.connected.emit(False)
    
    def write(self, data):
        if self.client:
            try:
                _, writer = self.client
                writer.write(data)
            except Exception as e:
                self.error.emit(str(e))
    
    def is_connected(self):
        return self.client is not None
    
    def get_connection_info(self):
        return f"Telnet - {self.host}:{self.port}"
    
    def _read_data(self):
        try:
            reader, _ = self.client
            import asyncio
            loop = asyncio.get_event_loop()
            data = loop.run_until_complete(reader.read(1024))
            if data:
                self.received.emit(data)
        except EOFError:
            if self._is_running:
                self.error.emit("连接已关闭")
            raise
        except Exception as e:
            if self._is_running:
                self.error.emit(str(e))
            raise